class YHTools {
  // struct func

  constructor(options) {
    // this.options = options;
  }
  //-----------------------
  getFixedNumber(options) {
    var value = options.value,
      length = options.length;
    var aNumber = new Number(value);
    var aNumberString = aNumber.toFixed(length);
    return aNumberString;
  }
  // check phone number
  chenckPhone(options) {
    var sMobile = options.phone;

    if (!/^1[0-9][0-9]\d{8}$/.test(sMobile)) {
      return false;
    } else {
      return true;
    }
  }
  // storge
  saveLocalData(options, asyncBol) {
    let now = new Date();
    if (asyncBol) {
      try {
        for (var key in options) {
          let value = {
            stime: now.getTime(),
            value: options[key],
          };
          wx.setStorage({
            key: key,
            data: value,
          });
        }
        return true;
      } catch (err) {
        return false;
      }
    } else {
      try {
        for (var key in options) {
          let value = {
            stime: now.getTime(),
            value: options[key],
          };
          wx.setStorageSync(key, value);
        }
        return true;
      } catch (err) {
        return false;
      }
    }
  }

  removeLocalData(options, asyncBol) {
    if (asyncBol) {
      try {
        wx.removeStorage({
          key: options,
          success: function (res) {},
        });
        return true;
      } catch (err) {
        return false;
      }
    } else {
      try {
        wx.removeStorageSync(options);
        return true;
      } catch (err) {
        return false;
      }
    }
  }

  getLocalData(options) {
    try {
      var value = wx.getStorageSync(options);
      if (value && value.value != "") {
        return {
          value: value.value,
          msg: "get value ok",
          stme: value.stime,
        };
      } else {
        return {
          value: false,
          msg: "has no value",
        };
      }
    } catch (err) {
      value = wx.getStorageSync(options);
      if (value && value.value != "") {
        return {
          value: value.value,
          msg: "get value ok",
          stme: value.stime,
        };
      } else {
        return {
          value: false,
          msg: "api error msg :" + JSON.stringify(err),
        };
      }
    }
  }

  delay(options) {
    setTimeout(options.func, options.time);
  }

  systemInfo() {
    var systemInfo = this.getLocalData("systemInfo").value;
    if (!systemInfo) {
      systemInfo = wx.getSystemInfoSync();
      this.saveLocalData({
        systemInfo: systemInfo,
      });
    }
    return systemInfo;
  }
  refreshLoginCode(callBack) {
    //待优化
    var that = this;
    // 登录

    wx.login({
      success: function (data) {
        var code = data.code;
        var now = new Date();
        var codeTime = now.getTime();

        that.saveLocalData({
          code: code,
          codeTime: codeTime,
        });
        if (callBack) {
          callBack();
        }
      },
      fail: function (fail) {
        console.warn("fail  = " + JSON.stringify(fail));
      },
    });

    return that.getLocalData("code").value;
  }

  netErr(msg, confirmColor) {
    wx.hideLoading();
    wx.showModal({
      title: "提示",
      content: msg || "请检查网络后重试！",
      showCancel: false,
    });
  }

  checkRes(options) {
    var httpCode = options.statusCode;
    if (httpCode == "401") {
      wx.showModal({
        title: "提示",
        content: "登录状态失效，请重新登录！",
        showCancel: false,
        success: function () {
          wx.clearStorageSync();
          wx.reLaunch({
            url: "/pages/SMSCodePage/SMSCodePage",
          });
        },
      });
      return false;
    } else {
      return true;
    }
  }
  // 日期补零
  checkDateFormatter(dateNum) {
    return dateNum > 9 ? dateNum : "0" + dateNum;
  }
  // 获得日期
  getDateStr(date, addOne) {
    var monthonFlag = addOne == 1 ? 0 : 1;
    return (
      date.getFullYear() +
      "-" +
      this.checkDateFormatter(date.getMonth() + monthonFlag) +
      "-" +
      this.checkDateFormatter(date.getDate()) +
      " " +
      this.checkDateFormatter(date.getHours()) +
      ":" +
      this.checkDateFormatter(date.getMinutes())
    );
  }
  // 获得日期 **年 **月 **日
  getDateStrHZ(date, addOne) {
    var monthonFlag = addOne == 1 ? 0 : 1;
    return (
      date.getFullYear() +
      "-" +
      this.checkDateFormatter(date.getMonth() + monthonFlag) +
      "-" +
      this.checkDateFormatter(date.getDate()) +
      " " +
      this.checkDateFormatter(date.getHours()) +
      ":" +
      this.checkDateFormatter(date.getMinutes())
    );
  }
  // 显示提示框
  showModal(options) {
    // 无取消键、无动作的提示
    var onlyTips = options.onlyTips;
    if (onlyTips) {
      wx.showModal({
        title: options.title,
        content: options.content,
        showCancel: false,
        success: function (res) {},
        fail: function (res) {},
      });
      return;
    }

    wx.showModal({
      title: options.title,
      content: options.content,
      showCancel: options.showCancel,
      success: function (res) {
        if (options.success) {
          options.success(res);
        }
      },
      fail: function (res) {
        if (options.fail) {
          options.fail(res);
        }
      },
      complete: function (res) {
        if (options.complete) {
          options.complete(res);
        }
      },
    });
  }

  returnFloatNum(num) {
    var strArr =
      (typeof num + "").toUpperCase() == "string" ?
      num.split(".") :
      num.toString().split(".");
    var strVal = strArr.pop();
    return strVal.length;
  }

  hasEmojiCharacter(substring) {
    for (var i = 0; i < substring.length; i++) {
      var hs = substring.charCodeAt(i);
      if (0xd800 <= hs && hs <= 0xdbff) {
        if (substring.length > 1) {
          var ls = substring.charCodeAt(i + 1);
          var uc = (hs - 0xd800) * 0x400 + (ls - 0xdc00) + 0x10000;
          if (0x1d000 <= uc && uc <= 0x1f77f) {
            return true;
          }
        }
      } else if (substring.length > 1) {
        var ls = substring.charCodeAt(i + 1);
        if (ls == 0x20e3) {
          return true;
        }
      } else {
        if (0x2100 <= hs && hs <= 0x27ff) {
          return true;
        } else if (0x2b05 <= hs && hs <= 0x2b07) {
          return true;
        } else if (0x2934 <= hs && hs <= 0x2935) {
          return true;
        } else if (0x3297 <= hs && hs <= 0x3299) {
          return true;
        } else if (
          hs == 0xa9 ||
          hs == 0xae ||
          hs == 0x303d ||
          hs == 0x3030 ||
          hs == 0x2b55 ||
          hs == 0x2b1c ||
          hs == 0x2b1b ||
          hs == 0x2b50
        ) {
          return true;
        } else {
          return false;
        }
      }
    }
  }

  checkAppVersion(callBack) {
    const that = this;
    wx.showLoading({
      title: "正在检查版本",
      mask: true,
    });
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        wx.hideLoading();
        updateManager.onUpdateReady(function () {
          if (callBack) {
            callBack();
          }
          updateManager.applyUpdate();
        });

        updateManager.onUpdateFailed(function () {
          wx.showModal({
            title: "更新失败",
            content: "请检查网络！",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                //     wx.reLaunch({
                //         url: "/pages/SMSCodePage/SMSCodePage",
                //     })
              }
            },
          });
        });
      } else {
        wx.hideLoading();
        const typeValue = typeof callBack;
        const upperCase = typeValue.toUpperCase();
        if (callBack && upperCase == "FUNCTION") {
          callBack();
        } else if (callBack && upperCase == "STRING") {
          that.showModal({
            title: "提示",
            content: callBack,
            showCancel: false,
          });
        }
      }
    });
  }
  compareVersion(v1, v2) {
    v1 = v1.split(".");
    v2 = v2.split(".");
    const len = Math.max(v1.length, v2.length);

    while (v1.length < len) {
      v1.push("0");
    }
    while (v2.length < len) {
      v2.push("0");
    }

    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i]);
      const num2 = parseInt(v2[i]);

      if (num1 > num2) {
        return 1;
      } else if (num1 < num2) {
        return -1;
      }
    }

    return 0;
  }
  checkSDKVersion(SDKVersion) {
    const that = this;
    const res = wx.getSystemInfoSync();
    const sdkVersion = res.SDKVersion;
    if (this.compareVersion(configVersion, sdkVersion) > 0) {
      that.showModal({
        title: "提示",
        content: "微信版本过低，请更新微信！",
        showCancel: false,
      });
      return false;
    } else {
      return true;
    }
  }

  // c s k x app tool func
  getStartEndPointFunc(peice) {
    var ftGetOnLocationFtSiteId =
      peice.ftGetOnLocationFtSiteId || peice.getOnLocationFtSiteId;
    var ftGetOffLocationFtSiteId =
      peice.ftGetOffLocationFtSiteId || peice.getOffLocationFtSiteId;
    var ftReSitesOfLine = peice.ftReSitesOfLine || peice.siteIdList;

    ftReSitesOfLine.forEach(function (point, index) {
      if (point.siteId == ftGetOnLocationFtSiteId) {
        peice.realyMemberStartPoint = point;
      }

      if (point.siteId == ftGetOffLocationFtSiteId) {
        peice.realyMemberEndPoint = point;
      }
    });
    return peice;
  }

  findObjFromArrByProperty(arrary, property, propertyBol) {
    if (propertyBol) {
      var key;
      for (var i in property) {
        key = i;
      }

      for (var i = 0; i < arrary.length; i++) {
        let item = arrary[i];
        if (item[key] == property[key]) {
          return item;
        }
      }
    } else {
      for (var i = 0; i < arrary.length; i++) {
        let item = arrary[i];
        if (item == property) {
          return item;
        }
      }
    }
  }

  saveCurrentPageToStack() {
    let [...pageStack] = getCurrentPages();
    this.saveLocalData({
      ppage: pageStack.pop().route,
    });
  }

  getStackPage() {
    return this.getLocalData("ppage").value;
  }

  getCurrentPage() {
    let [...pageStack] = getCurrentPages();
    return pageStack.pop().route;
  }

  getUrlParsByObj(obj) {
    var urPar = "";
    for (var key in obj) {
      var value = obj[key];
      if (typeof value == "object") {
        var v = JSON.stringify(value);
        v = v.replace("&", "%26");
        v = v.replace("=", "%3D");
        urPar = urPar + key + "=" + v + "&";
      } else {
        if (isNaN(value)) {
          value = value ? value : "undefined";
          value = value.replace("&", "%26");
          value = value.replace("=", "%3D");
        }
        urPar = urPar + key + "=" + value + "&";
      }
    }
    return urPar.substr(0, urPar.length - 1);
  }

  decodeUrlString(str) {
    if (typeof str == "string") {
      str = str.replace("%26", "&");
      str = str.replace("%3D", "=");
    }
    return str;
  }

  cUrlToJson(urlC) {
    let urlComponents = decodeURIComponent(urlC.split("?").pop()).split("&");
    var obj = {};
    urlComponents.forEach(function (item) {
      let itemComponents = item.split("=");
      obj[itemComponents[0]] = itemComponents[1];
    });
    return obj;
  }

  yhSetPageData(key, value, type, subKey1, subKey2) {
    var pages = getCurrentPages();
    var currentPage = pages[pages.length - 1],
      keyTemp;
    if (type != undefined) {
      let typeUper = type.trim().toUpperCase();
      switch (typeUper) {
        case "A": {
          if (subKey1 != undefined) {
            keyTemp = key + "[" + subKey1 + "]." + subKey2;
          } else {
            keyTemp = key + "[" + subKey1 + "]";
          }
        }
        break;
      case "O": {
        keyTemp = key + "." + subKey;
      }
      break;
      default: {}
      break;
      }
    } else {
      keyTemp = key;
    }
    var obj = new Object();
    obj[keyTemp] = value;
    currentPage.setData(obj);
  }

  arraryDelectObjects(options) {
    /*
         const arrary = arraryDelectObjects({
            arrary: arrary,
            property: {
              id: obj.id,
            },
            length: 1,
          });
          */
    let i = -1,
      k = Object.keys(options.property)[0],
      v = options.property[k];
    for (let index = 0; index < options.arrary.length; index++) {
      const element = options.arrary[index];
      if (element[k] === v) {
        i = index;
        break;
      }
    }
    if (i !== -1) {
      options.arrary.splice(i, options.length);
      return options.arrary;
    } else {
      return false;
    }
  }

  arraryGetItemByItemProperty(arrary, prperty) {
    if (!arrary) {
      console.error("has no arrary!");
      return false;
    }
    var keyt,
      keyIn = 0;
    for (var key in prperty) {
      if (keyIn >= 1) {
        console.error("prperty has too much keys!");
        return false;
      }
      keyt = key;
      keyIn += 1;
    }
    let objvalue = false;
    for (var index in arrary) {
      let obj = arrary[index];
      for (var key in obj) {
        if (key == keyt && obj[key] == prperty[keyt]) {
          return obj;
        }
      }
    }
    return objvalue;
  }
  // 禁止重复点击
  /*
  options:{
    page:page,
    event:event,
    duration:duration
  }

  return :false 不是重复点击  ture：是重复点击
  */
  checkMultipleAction(options) {
    if (!options.hasOwnProperty("event")) {
      console.error("YHTOOLS - checkMultipleAction must have event args !");
      return;
    }
    if (!options.hasOwnProperty("page")) {
      console.error("YHTOOLS - checkMultipleAction must have event page !");
      return;
    }
    var d = options.hasOwnProperty("duration") ? options["duration"] : 400;
    var idf = "YH" + options.event;
    var page = options.page;
    var now = new Date().getTime();
    if (!page.hasOwnProperty(idf)) {
      page[idf] = now;
      return false;
    } else {
      let tm = page[idf];
      let bt = now - tm < d;
      page[idf] = now;
      if (bt) {
        wx.showToast({
          title: "请勿重复点击",
          icon: "none",
          image: "",
          duration: 1000,
          mask: false,
          success: (result) => {},
          fail: () => {},
          complete: () => {},
        });
      }
      return bt;
    }
  }

  objSetByObj(options) {
    // options = {handleO:handleO,valueO:valueO}
    var handleO = options.handleO;
    var valueO = options.valueO;
    for (const key in handleO) {
      if (valueO.hasOwnProperty(key)) {
        handleO[key] = valueO[key];
      }
    }
    return handleO;
  }
  // get week day
  getWeekDayHZ(date) {
    var weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var mon = weeks[date.getDay()];
    return mon;
  }
  // ellipsis str
  ellipsisStr(parms) {
    if (!parms.hasOwnProperty("str")) {
      console.error(
        "-YHTOOLS TIPS : function -ellipsisStr- must has prams named str"
      );
    }
    if (!parms.hasOwnProperty("len")) {
      console.error(
        "-YHTOOLS TIPS : function -ellipsisStr- must has prams named len"
      );
    }
    return parms.str.length > parms.len ?
      parms.str.substr(0, parms.len) + "..." :
      parms.str;
  }
  // toRoundfixed
  roundFixed(parms) {
    if (!parms.hasOwnProperty("num")) {
      console.error(
        "-YHTOOLS TIPS : function -ellipsisStr- must has prams named str"
      );
    }
    if (!parms.hasOwnProperty("count")) {
      console.error(
        "-YHTOOLS TIPS : function -ellipsisStr- must has prams named len"
      );
    }
    if (parms.count == 0) {
      return Math.round(parms.num);
    }
    var m = Math.pow(10, parms.count);
    var n = Math.round(parms.num * m) / m;
    return n.toFixed(parms.count);
  }
  // hid num str
  hideMiddlePhone(string) {
    return string.substr(0, 3) + "****" + string.substr(3, 4);
  }

  proxySet(prox, objs) {
    const keys = Object.keys(objs);
    for (let index = 0; index < keys.length; index++) {
      const key = keys[index];
      prox[key] = objs[key]
    }
  };

}

// Object.prototype.proxySet = function (objs) {
//   const keys = Object.keys(objs);
//   for (let index = 0; index < keys.length; index++) {
//     const key = keys[index];
//     this[key] = objs[key]
//   }
// };

String.prototype.replaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
}




module.exports = YHTools;